<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>客户活跃统计</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="/css/public.css" media="all">
    <style>
        .statistics-container {
            padding: 20px;
        }
        .statistics-section {
            margin-bottom: 30px;
            background: #fff;
            border-radius: 4px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .section-title {
            font-size: 18px;
            font-weight: bold;
            padding: 15px 20px;
            border-bottom: 1px solid #e6e6e6;
            background: #f8f8f8;
            margin: 0;
        }
        .table-container {
            padding: 20px;
        }
        .pagination-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 15px;
            padding: 10px 0;
        }
        .pagination-controls {
            display: flex;
            align-items: center;
        }
        .pagination-controls button {
            margin: 0 2px;
            padding: 5px 10px;
            border: 1px solid #ddd;
            background: #fff;
            cursor: pointer;
        }
        .pagination-controls button:hover {
            background: #f0f0f0;
        }
        .pagination-controls button.active {
            background: #1E9FFF;
            color: #fff;
            border-color: #1E9FFF;
        }
        .pagination-controls button:disabled {
            background: #f5f5f5;
            color: #ccc;
            cursor: not-allowed;
        }
    </style>
</head>
<body>
<div class="layuimini-container" id="app">
    <div class="layuimini-main">
        <!-- 查询条件模块 -->
        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="" lay-filter="table-search">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">平台:</label>
                            <div class="layui-input-inline">
                                <select name="platform" class="layui-select">
                                    <option value="">全部</option>
                                    <option v-for="(item,index) in platforms" :value="item.id">{{item.name}}</option>
                                </select>
                            </div>
                            </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">服务器:</label>
                            <div class="layui-input-inline">
                                <select name="server" class="layui-select">
                                    <option value="">全部</option>
                                    <option v-for="(item,index) in services" :value="item.id">{{item.name}}</option>
                                </select>
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">时间范围:</label>
                            <div class="layui-input-inline">
                                <select name="timeRange" class="layui-select" @change="onTimeRangeChange">
                                    <option value="">自定义</option>
                                    <option value="today">今日</option>
                                    <option value="yesterday">昨日</option>
                                    <option value="week">近一周</option>
                                    <option value="month">近一个月</option>
                                </select>
                            </div>
                        </div>

                            <div class="layui-inline">
                                <label class="layui-form-label">记录时间</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="createDateTimeBegin" id="createTime0"
                                           placeholder="开始时间" autocomplete="off" class="layui-input" />
                                    <input type="text" name="createDateTimeEnd" id="createTime1"
                                           placeholder="截止时间" autocomplete="off" class="layui-input" />
                                </div>
                            </div>

                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary" lay-submit lay-filter="data-search-btn">
                                <i class="layui-icon">&#xe615;</i> 搜 索
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <div class="statistics-container">
            <!-- 活跃统计 -->
            <div class="statistics-section">
                <h3 class="section-title">活跃统计</h3>
                <div class="table-container">
                    <table class="layui-table" lay-skin="line">
                        <thead>
                            <tr>
                                <th>日期</th>
                                <th>DAU</th>
                                <th>WAU</th>
                                <th>MAU</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="item in activeStats" :key="item['日期']">
                                <td>{{ item['日期'] }}</td>
                                <td>{{ item['DAU'] }}</td>
                                <td>{{ item['WAU'] }}</td>
                                <td>{{ item['MAU'] }}</td>
                            </tr>
                        </tbody>
                    </table>
                    <div class="pagination-info">
                        <div>
                            <select v-model="activeStatsPageSize" @change="loadActiveStats">
                                <option value="10">10条</option>
                                <option value="20">20条</option>
                                <option value="50">50条</option>
                            </select>
                            <span>条记录 (共计{{ activeStatsTotal }}条)</span>
                        </div>
                        <div class="pagination-controls">
                            <button @click="goToActiveStatsPage(1)" :disabled="activeStatsCurrentPage === 1">|&lt;</button>
                            <button @click="goToActiveStatsPage(activeStatsCurrentPage - 1)" :disabled="activeStatsCurrentPage === 1">&lt;</button>
                            <button v-for="page in getActiveStatsPageNumbers()" 
                                    :key="page" 
                                    @click="goToActiveStatsPage(page)"
                                    :class="{ active: page === activeStatsCurrentPage }">{{ page }}</button>
                            <button @click="goToActiveStatsPage(activeStatsCurrentPage + 1)" :disabled="activeStatsCurrentPage === activeStatsTotalPages">&gt;</button>
                            <button @click="goToActiveStatsPage(activeStatsTotalPages)" :disabled="activeStatsCurrentPage === activeStatsTotalPages">&gt;|</button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 首次游戏时长 -->
            <div class="statistics-section">
                <h3 class="section-title">游戏时长</h3>
                <div class="table-container">
                    <table class="layui-table" lay-skin="line">
                        <thead>
                            <tr>
                                <th>游戏时长</th>
                                <th>玩家人数</th>
                                <th>占比</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="item in gameDurationStats" :key="item.duration">
                                <td>{{ item.duration }}</td>
                                <td>{{ item.playerCount }}</td>
                                <td>{{ item.percentage }}</td>
                            </tr>
                        </tbody>
                    </table>
    </div>
</div>

            <!-- 游戏次数 -->
            <div class="statistics-section">
                <h3 class="section-title">游戏次数</h3>
                <div class="table-container">
                    <table class="layui-table" lay-skin="line">
                        <thead>
                            <tr>
                                <th>启动游戏次数</th>
                                <th>人数</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="item in gameCountStats" :key="item.count">
                                <td>{{ item.count }}</td>
                                <td>{{ item.playerCount }}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="/lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="/js/common.js?v=5" charset="utf-8"></script>
<script src="/js/vue.min.js" charset="utf-8"></script>
<script>
    var channels = getEnum('channel');

    new Vue({
        el: "#app",
        data: {
            // 查询条件数据
            platforms: [       { id: '1', name: '安卓'},
                { id: '2', name: '苹果'},
                { id: '3', name: 'PC' },
        ],
            services: (() => {
                try {
                    const data = localStorage.getItem('services');
                    return data ? JSON.parse(data) : [];
                } catch (e) {
                    console.error('解析 services 数据失败:', e);
                    return [];
                }
            })(),

            // 活跃统计数据
            activeStats: [],
            activeStatsCurrentPage: 1,
            activeStatsPageSize: 10,
            activeStatsTotal: 0,
            activeStatsTotalPages: 0,

            // 首次游戏时长数据
            gameDurationStats: [
                { duration: '1天', playerCount: '', percentage: '' },
                { duration: '2天', playerCount: '', percentage: '' },
                { duration: '3天', playerCount: '', percentage: '' },
                { duration: '4~7天', playerCount: '', percentage: '' },
                { duration: '8~15天', playerCount: '', percentage: '' },
                { duration: '16~30天', playerCount: '', percentage: '' },
                { duration: '31天+', playerCount: '', percentage: '' }

            ],

            // 游戏次数数据
            gameCountStats: [
                { count: '1', playerCount: '' },
                { count: '2~3', playerCount: '' },
                { count: '4~7', playerCount: '' },
                { count: '8~15', playerCount: '' },
                { count: '15次+', playerCount: '' }
            ]
        },
        methods: {
            // 时间范围快速选择
            onTimeRangeChange(event) {
                const timeRange = event.target.value;
                const now = new Date();
                let startTime, endTime;

                switch (timeRange) {
                    case 'today':
                        startTime = new Date(now.getFullYear(), now.getMonth(), now.getDate());
                        endTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59);
                        break;
                    case 'yesterday':
                        const yesterday = new Date(now);
                        yesterday.setDate(yesterday.getDate() - 1);
                        startTime = new Date(yesterday.getFullYear(), yesterday.getMonth(), yesterday.getDate());
                        endTime = new Date(yesterday.getFullYear(), yesterday.getMonth(), yesterday.getDate(), 23, 59, 59);
                        break;
                    case 'week':
                        startTime = new Date(now);
                        startTime.setDate(startTime.getDate() - 7);
                        endTime = now;
                        break;
                    case 'month':
                        startTime = new Date(now);
                        startTime.setDate(startTime.getDate() - 30);
                        endTime = now;
                        break;
                    default:
                        return;
                }

                // 设置时间输入框的值
                document.getElementById('createTime0').value = this.formatDateTime(startTime);
                document.getElementById('createTime1').value = this.formatDateTime(endTime);
            },

            // 格式化日期时间
            formatDateTime(date) {
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');
                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            },

            // 加载活跃统计数据
            loadActiveStats() {
                const formData = this.getFormData();
                formData.page = this.activeStatsCurrentPage;
                formData.limit = this.activeStatsPageSize;

                layui.jquery.get('/admin/customer/activeUserStats', formData, (res) => {
                    if (res.code !== 0) {
                        layui.layer.msg(res.msg, {icon: 2});
                        return;
                    }
                    
                    this.activeStats = res.data || [];
                    // 由于新接口没有分页信息，我们使用数据长度作为总数
                    this.activeStatsTotal = res.data ? res.data.length : 0;
                    this.activeStatsTotalPages = Math.ceil(this.activeStatsTotal / this.activeStatsPageSize);
                }).fail(() => {
                    layui.layer.msg('活跃统计数据加载失败', {icon: 2});
                });
            },

            // 加载游戏次数统计数据
            loadGameTimesStats() {
                const formData = this.getFormData();

                layui.jquery.get('/admin/customer/gameTimesStats', formData, (res) => {
                    if (res.code !== 0) {
                        layui.layer.msg(res.msg, {icon: 2});
                        return;
                    }
                    
                    // 转换数据格式以匹配页面显示
                    this.gameCountStats = (res.data || []).map(item => ({
                        count: item['启动游戏次数'],
                        playerCount: item['人数']
                    }));
                }).fail(() => {
                    layui.layer.msg('游戏次数统计数据加载失败', {icon: 2});
                });
            },

            // 加载游戏时长统计数据
            loadGameTimes() {
                const formData = this.getFormData();

                layui.jquery.get('/admin/customer/gameTimes', formData, (res) => {
                    if (res.code !== 0) {
                        layui.layer.msg(res.msg, {icon: 2});
                        return;
                    }

                    // 转换数据格式以匹配页面显示
                    this.gameDurationStats = (res.data || []).map(item => ({
                        duration: item['游戏时长'],
                        playerCount: item['人数'],
                        percentage: item['占比']

                    }));
                }).fail(() => {
                    layui.layer.msg('游戏次数统计数据加载失败', {icon: 2});
                });
            },

            // 获取表单数据
            getFormData() {
                // 使用表单序列化确保所有筛选项都被采集并随请求传递
                var $ = layui.jquery;
                var formArray = $('form[lay-filter="table-search"]').serializeArray();
                var data = {};
                for (var i = 0; i < formArray.length; i++) {
                    var item = formArray[i];
                    // 只收集非空值，避免把空字符串传给后端
                    if (item && item.name) {
                        if (item.value !== undefined && item.value !== null && item.value !== '') {
                            data[item.name] = item.value;
                        }
                    }
                }
                return data;
            },

            // 搜索数据
            searchData() {
                this.activeStatsCurrentPage = 1;
                this.loadActiveStats();
                this.loadGameTimesStats();
                this.loadGameTimes();
            },

            // 活跃统计分页相关方法
            goToActiveStatsPage(page) {
                if (page >= 1 && page <= this.activeStatsTotalPages) {
                    this.activeStatsCurrentPage = page;
                    this.loadActiveStats();
                }
            },
            
            getActiveStatsPageNumbers() {
                const pages = [];
                const start = Math.max(1, this.activeStatsCurrentPage - 2);
                const end = Math.min(this.activeStatsTotalPages, this.activeStatsCurrentPage + 2);
                
                for (let i = start; i <= end; i++) {
                    pages.push(i);
                }
                return pages;
            }
        },
        mounted: function() {
            var vm = this;
            layui.use(['form', 'laydate', 'layer'], function() {
                var $ = layui.jquery,
                    form = layui.form,
                    laydate = layui.laydate,
                    layer = layui.layer;

                // 初始化日期选择器
                laydate.render({
                    elem: '#createTime0',
                    type: 'datetime',
                    value: getYmd(0) + " 00:00:00"
                });
                
                laydate.render({
                    elem: '#createTime1',
                    type: 'datetime',
                    value: getYmd(1) + " 00:00:00"
                });

                // 监听搜索按钮
                form.on('submit(data-search-btn)', function(data) {
                    vm.searchData();
                    return false;
                });

                // 初始化数据
                vm.loadActiveStats();
                vm.loadGameTimesStats();
                vm.loadGameTimes();
            });
        }
    });

    // 获取日期字符串的辅助函数
    function getYmd(days) {
        const date = new Date();
        date.setDate(date.getDate() + days);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    }
</script>
</body>
</html>